﻿Public Class Window : Inherits Panel

	Public Tab As TabStrip.Tab
	Public Local As New Token(Me)
	Public Remote As New Token(Me)
	Public HistoryBack As New Stack(Of Page)
	Public HistoryForward As New Stack(Of Page)
	Public Menu As Menu

	Public Tables As New SortedList(Of String, Recordset)
	'Public ssd As New ssdDataContext
	Dim WithEvents ToolStrip As New ToolStrip

	Sub New()
		Themes.Register(Me)
		Menu = New Menu(Me)
		Dock = DockStyle.Fill
		ToolStrip.Renderer = New FirefoxRenderer
		Controls.Add(ToolStrip)
		ToolStrip.Dock = DockStyle.Top
		ToolStrip.Padding = New Padding(5, 4, 5, 4)
		ToolStrip.ImageScalingSize = New Size(19, 19)
		ToolStrip.BackColor = Color.FromArgb(200, 208, 224)
		ToolStrip.SendToBack()
		ToolStrip.AddButton("back", "", My.Resources.goback)
		ToolStrip.AddButton("forward", "", My.Resources.goforward)
		ToolStrip.AddSeperator()
		ToolStrip.AlwaysFlat = False
		Dim t = New ToolStripSpring(AddressBox)
		ToolStrip.Items.Add(t)
		t.Overflow = ToolStripItemOverflow.Never
		ToolStrip.AddButton("-refresh", "", My.Resources.refresh)
		ToolStrip.AddButton("-home", "", My.Resources.home)
		ToolStrip.AddButton("-search", "", My.Resources.search)
		ToolStrip.AddButton("-+settings", "", My.Resources.settings)
		ToolStrip.AddButtonMenu("settings", "password", "Parola değişikliği...")
		ToolStrip.AddButtonMenu("settings", "-", "-")
		ToolStrip.AddButtonMenu("settings", "settings", "Ayarlar...")
		ToolStrip.CanOverflow = False
		ToolStrip.Refresh()
		SetNavigationButtons()
#If Not Browser Then
		ToolStrip.Visible = False
#End If
	End Sub

	Public AddressBox As New AddressBox

	Sub Launch(Menu As MenuItem, Type As Type, Arguments As String, Central As Boolean)
		Dim Process As Process = Activator.CreateInstance(Type)
		If Arguments <> "" Then Process.QueryString = Arguments
		Process.Menu = Menu
		Launch(Process, False)
	End Sub

	Sub Launch(Address As String)
		Dim Page = New BrowserPage
		Launch(Page)
		AddressBox.Page = Page
		Page.Navigate(Address)
	End Sub

	Sub Launch(Menu As MenuItem)
		Launch(Menu.GetPage, False)
	End Sub

	Sub Launch(Page As Page, Optional IsDialog As Boolean = False)
		If Not User.Valid Then
			Warning("Uygulamayı kullanmak için giriş yapmanız gerekiyor.")
			Return
		End If
		Connect()
		Page.Caller = ActivePage
		If TypeOf Page Is Process Then
			CType(Page, Process).BranchSelection = (Not Page.Menu Is Nothing AndAlso Page.Menu.Local = "E") AndAlso User.Department.ID = "0"
		End If
		SuspendLayout()
		HistoryBack.Push(Page)
		HistoryForward.Clear()
		If IsDialog OrElse (TypeOf Page Is ProcessBase AndAlso Not CType(Page, ProcessBase).Maximized) Then
			SnapshotWindow()
		End If
		Controls.Add(Page)
		SetNavigationButtons()
		If IsDialog Or (TypeOf Page Is ProcessBase AndAlso Not CType(Page, ProcessBase).Maximized) Then
			Page.Location = New Point((Width - Page.Width) \ 2, ToolStrip.Height + (Height - ToolStrip.Height - Page.Height) \ 2)
			Page.Anchor = AnchorStyles.None
			Invalidate()
		Else
			Page.Size = ClientRectangle.Size
			Page.Dock = DockStyle.Fill
			Page.BringToFront()
		End If
		DisplayActivePage()
		If Not Page.Caller Is Nothing Then
			Page.Caller.Visible = False
			Page.Caller.SendToBack()
		End If
		ResumeLayout()
	End Sub

	Protected Overrides Sub OnSizeChanged(e As System.EventArgs)
		MyBase.OnSizeChanged(e)
		SuspendLayout()
		SnapshotWindow()
		ResumeLayout()
	End Sub

	Sub SnapshotWindow()
		If HistoryBack.Count < 2 Then Return
		Dim Snapshot As New Bitmap(ClientRectangle.Width, ClientRectangle.Height)
		Dim R = ClientRectangle
		R.Height -= ToolStrip.Height
		R.Offset(0, ToolStrip.Height)
		HistoryBack(1).Size = R.Size
		HistoryBack(1).DrawToBitmap(Snapshot, R)
		Dim Snapshot2 As New Bitmap(ClientRectangle.Width \ 2, ClientRectangle.Height \ 2)
		Dim G = Graphics.FromImage(Snapshot2)
		G.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBilinear
		G.DrawImage(Snapshot, New Rectangle(0, 0, Snapshot2.Width, Snapshot2.Height))
		BackgroundImage = Snapshot2
		BackgroundImageLayout = ImageLayout.Stretch
	End Sub

	ReadOnly Property ActivePage As Page
		Get
			If HistoryBack.Count = 0 Then Return Nothing
			Return HistoryBack.Peek
		End Get
	End Property

	ReadOnly Property Image As Image
		Get
			If HistoryBack.Count > 0 Then
				If TypeOf ActivePage Is ProcessReport Then Return My.Resources.bwreport
				If TypeOf ActivePage Is ProcessHelp Then Return My.Resources.bwhelp
				If TypeOf ActivePage Is ProcessSearch Then Return My.Resources.bwsearch
				If TypeOf ActivePage Is Process Then Return My.Resources.bwform
				If TypeOf ActivePage Is MenuPage Then Return CType(ActivePage, MenuPage).Menu.Image
				If TypeOf ActivePage Is BrowserPage Then Return CType(ActivePage, BrowserPage).Image
			End If
			If Controls.Count > 0 AndAlso TypeOf Controls(0) Is Homepage Then Return My.Resources.ssd2
			Return Nothing
		End Get
	End Property

	Sub Close()
		SuspendLayout()
		Dim Process As Process = HistoryBack.Pop
		Controls.Remove(Process)
		If Controls.Count = 1 Then
			Tab.Close()
			Return
		End If
		DisplayActivePage()
		SetNavigationButtons()
		ResumeLayout()
		BackgroundImage = Nothing
	End Sub

	Sub DisplayActivePage()
		Tab.Text = ActivePage.Text
		ActivePage.Visible = True
		ActivePage.BringToFront()
		If Not ActivePage.Menu Is Nothing Then AddressBox.Menu = ActivePage.Menu
		FindForm.ActiveControl = ActivePage.ActiveControl
		If TypeOf ActivePage Is ProcessBase Then CType(ActivePage, ProcessBase).FocusLast()
		If Not FindForm.ActiveControl Is Nothing Then
			FindForm.ActiveControl.Focus()
		Else
			ActivePage.Focus()
			FindForm.ActiveControl = ActivePage
		End If
	End Sub

	Sub ClearAndLaunch(Process As Process)
		Do Until HistoryBack.Count = 0
			Close()
		Loop
		Launch(Process)
	End Sub

	Sub CloseAndLaunch(Process As Process)
		SuspendLayout()
		Dim OldProcess As Process = HistoryBack.Pop
		Controls.Remove(OldProcess)
		Launch(Process)
		'DisplayActivePage()
		'SetNavigationButtons()
		ResumeLayout()
		'BackgroundImage = Nothing
	End Sub

	Function HasProcesses() As Boolean
		Return HistoryBack.Count > 0
	End Function

	Public Function CurrentLocalDepartment() As Integer
		Dim LocalServer = Department.ID
		If LocalServer = 0 Then LocalServer = BranchSelection
		Return LocalServer
	End Function

	Dim BranchSelection = 1
	Public Sub Connect()
		Dim LocalServer = CurrentLocalDepartment()
		Dim Online As Boolean = Database.TestConnection(True, LocalServer, 5000)
		If Not Online Then Warning(Department.SubeAdi(LocalServer) & " şubesi ile bağlantı kurulamadı. Merkez üzerinden bağlanılacak.")
		Local.Open(Database.ConnectionString(Online, LocalServer), Nothing)
		Remote.Open(Database.ConnectionString(True, 0), Nothing)
	End Sub
	Sub Connect(Server As Integer)
		BranchSelection = Server
		Connect()
	End Sub

	ReadOnly Property Department() As Department
		Get
			Return User.Department
		End Get
	End Property

	Protected Overrides Sub OnPaint(e As System.Windows.Forms.PaintEventArgs)
		MyBase.OnPaint(e)
		If ActivePage Is Nothing Then Exit Sub
		If ActivePage.Dock = DockStyle.Fill Then Exit Sub
		e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.None
		e.Graphics.FillRectangle(New SolidBrush(Color.FromArgb(0.5 * 255, Color.Black)), ClientRectangle)
		e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
		Dim R As Rectangle = ActivePage.Bounds
		For rd = 1 To 23 Step 2
			Dim Pen As New Pen(Color.Black.Opacity(64 / rd), rd)
			e.Graphics.DrawRoundRect(R, Pen, 1)
		Next
	End Sub

	Private Sub ToolStrip_ItemClicked(sender As Object, e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles ToolStrip.ItemClicked
		If e.ClickedItem.Name = "home" Then
			Launch(New Homepage)
		ElseIf e.ClickedItem.Name = "back" Then
			GoBack()
		ElseIf e.ClickedItem.Name = "forward" Then
			GoForward()
		ElseIf e.ClickedItem.Name = "search" Then
			Search()
		End If
	End Sub

	Sub Search(Optional Type As Integer = 0)
		'Dim Process As New QuickSearch
		'Process.AddArgument("type", Type)
		'Launch(Process, True)
		Dim Window = FrmMain.AddWindow()
		Select Case Type
			Case 1 : Window.Launch(New SigortaliBilgileri)
			Case 2 : Window.Launch(New IsyeriBilgileri)
		End Select
		'Launch(New isyeri
	End Sub

	Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, keyData As System.Windows.Forms.Keys) As Boolean
		Select Case keyData
			Case Keys.F3
				Search(1)
				Return True
			Case Keys.F6
				Search(2)
				Return True
			Case Keys.Alt + Keys.D
				AddressBox.Edit()
		End Select
		Return MyBase.ProcessCmdKey(msg, keyData)
	End Function

	Private Sub SetNavigationButtons()
		ToolStrip.Items("back").Enabled = HistoryBack.Count > 1
		ToolStrip.Items("forward").Enabled = HistoryForward.Count > 0
		ToolStrip.Rearrange()
	End Sub

	Sub GoBack()
		If Not ToolStrip.Items("back").Enabled Then Return
		SuspendLayout()
		HistoryForward.Push(HistoryBack.Pop)
		DisplayActivePage()
		HistoryForward.Peek.Visible = False
		SetNavigationButtons()
		ResumeLayout()
	End Sub

	Sub GoForward()
		If Not ToolStrip.Items("forward").Enabled Then Return
		SuspendLayout()
		ActivePage.Visible = False
		HistoryBack.Push(HistoryForward.Pop)
		DisplayActivePage()
		SetNavigationButtons()
		ResumeLayout()
	End Sub

	Sub ClassicView()
		For Each Control As Control In Controls
			If TypeOf Control Is Homepage Then
				Control.Visible = True
				Control.BringToFront()
				Return
			End If
		Next
		For Each Control As Control In Controls
			If TypeOf Control Is MenuPage Then
				Controls.Remove(Control)
				Control = Nothing
			End If
		Next
	End Sub

	Sub ShowContextMenu(Control As Control, e As MouseEventArgs)
		Dim Menu As New ContextMenuStrip
		Menu.Renderer = New Renderer
		Dim Back = Menu.Items.Add("Geri dön", My.Resources.goback, AddressOf GoBack)
		Dim Forward = Menu.Items.Add("İleri", My.Resources.goforward, AddressOf GoForward)
		Dim Refresh = Menu.Items.Add("Sayfayı yenile", My.Resources.refresh, AddressOf RefreshPage)
		Menu.Items.Add("-")
		Dim Customize = Menu.Items.Add("Özelleştir...", Nothing, AddressOf Me.Customize)
		Back.Enabled = ToolStrip.Items("back").Enabled
		Forward.Enabled = ToolStrip.Items("forward").Enabled
		Refresh.Enabled = TypeOf ActivePage Is BrowserPage
		Customize.Enabled = False
		Menu.Show(Control, e.Location)
	End Sub

	Sub RefreshPage()
		If TypeOf ActivePage Is BrowserPage Then
			CType(ActivePage, BrowserPage).RefreshPage()
		End If
	End Sub
	Dim _Mode As EditMode = EditMode.Default
	Property Mode As EditMode
		Get
			Return _Mode
		End Get
		Set(value As EditMode)
			_Mode = value
			Select Case Mode
				Case EditMode.Customize
					SuspendLayout()
					Dim Panel As New Panel
					Controls.Add(Panel)
					Panel.Dock = DockStyle.Bottom
					Panel.SendToBack()
					Panel.Height = 24 + 12
					Dim Button1 = New Button With {.Size = New Size(72, 24), .Text = "Kaydet", .ImageKey = "save", .Anchor = AnchorStyles.Right + AnchorStyles.Bottom, .TabStop = False}
					Dim Button2 = New Button With {.Size = Button1.Size, .Text = "Vazgeç", .ImageKey = "cancel", .Anchor = AnchorStyles.Right + AnchorStyles.Bottom, .TabStop = False}
					Button2.Location = New Point(Panel.Width - Button2.Width - 6, 6)
					Button1.Location = New Point(Button2.Left - Button1.Width - 6, 6)
					Panel.Controls.Add(Button1)
					Panel.Controls.Add(Button2)
					Panel.BackColor = Color.Black
					ResumeLayout()
					Dim Label As New Windows.Forms.Label
					'Label.Font = H1Font
					Label.ForeColor = Color.White
					Label.AutoSize = True
					Label.Text = "Değiştirmek istediğiniz öğeye tıklayın. Değişiklikleri tamamlayınca Kaydet butonuyla kaydedin."
					Label.Location = New Point(8, 10)
					panel.Controls.Add(Label)
					Invalidate()
			End Select
		End Set
	End Property

	Enum EditMode
		[Default]
		Customize
	End Enum

	Private Sub Customize()
		Mode = EditMode.Customize
	End Sub

End Class

